<?php
/**
 * Управление пользователями, а так же их контроль, и распределение прав/обязанностей
 * 
 * @version 0.1 alpha
 * @package xine Framework http://lolbe.ru/360/xineFramework/
 * @author RiderSx <alexridersx@gmail.com>
 */

/**
 * Factory class
 */
 class xineUsers {
 	private $storage, $cache, $thisUser;
 	
 	private $authorized=false;
 	
 	public function __init ($storage=null, $cache=null, $forceSessionStart=false) {
 		$this->storage = $storage;
 		
 		if(null === $cache) {}
 		else {
 			$this->cache =& xine::$cache;
 		}
 		
 		if($forceSessionStart) $this->start();
 	}
 	
 	public function start () {
 		session_start();
 		
 		if(!isset($_SESSION['UID']) && isset($_COOKIE['__acss'])) {
 			$this->thisUser = $this->authByCookie();
 			$this->authorized = true;
 		}
 	}
 	
 	public function stop () {
 		session_write_close();
 	}
 	
 	public function isAuth () {
 		return $this->authorized;
 	}
 	
 	public function getUser ($identifier) {
 		$user &= $this->cache->get('UID_'.$identifier);
 		
 		if($user) {
 			return $user;
 		} else {
 			$user &= $this->storage->getUser($identifier);
 			$this->cache->set('UID_'.$identifier, $user);
 			
 			return $user;
 		}
 	}
 	
 	public function updateUser ($identifier, $data=array()) {
 		if($this->storage->updateUser($identifier)) {
 			if($this->cache->store('UID_'.$identifier, $this->getUser($identifier))) {
 				return true;
 			} else {
 				return false;
 			}
 		} else {
 			return false;
 		}
 	}
 	
 	public function checkUserName ($name) {
 		preg_match("/[a-zA-Z0-9._-]*$/", $name, $matches);
 		
 		if(!empty($matches[0][0])) {
 			return true;
 		} else {
 			return false;
 		}
 	}
 	
 	public function registerUser ($name, $email, $password, $openid=false) {
 		if($openid) {
 			
 		}
 	}
 	
 	public function authByIdentifier ($identifier, $password) {
 		if($this->storage->checkUser($identifier, $password)) {
 			$_SESSION['UID'] = $identifier;
 			return $this->getUser($identifier);
 		} else {
 			return false;
 		}
 	}
 	
 	public function authByCookie () {
 		$str = $_COOKIE['__acss'];
 		$data = explode(':', $str);
 		
 		return $this->authByIdentifier($data[0], $data[1]);
 	}
 }